package com.muyu.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ValidAspect
 * @Author: Zirun.Xin
 * @Date: 2025/4/7 下午4:00
 * @Version: 1.0
 * @Description: 校验切面
 */
@Aspect
@Component
public class ValidAspect {

    /**
     * 校验切面
     * @param pjp 切入点
     * @return 切入方法返回内容
     * @throws Throwable 异常签名
     */
    @Around(value = "execution(public * com.muyu.controller.UpgradeUserController.*(..)) || " +
            "execution(public * com.muyu.controller.CompanyController.*(..))")
    public Map<String, String> validAspect1(ProceedingJoinPoint pjp) throws Throwable {
        BindingResult bindingResult = getBindingResult(pjp);

        // 表示正常返回
        if(bindingResult == null || !bindingResult.hasErrors()) {
            Map<String, String> map = (Map<String, String>) pjp.proceed(pjp.getArgs());
            return map;
        } else {
            // 捕捉异常，将异常封装到map返回
            Map<String, String> map = new HashMap<>();
            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            fieldErrorList.forEach(fieldError -> map.put(fieldError.getField(), fieldError.getDefaultMessage()));
            return map;
        }
    }

    /**
     * 获取接口中的BindingResult对象
     * @param pjp 切入点
     * @return BindingResult实例
     */
    private BindingResult getBindingResult(ProceedingJoinPoint pjp) {
        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            if(arg instanceof BindingResult) {
                return (BindingResult) arg;
            }
        }
        return null;
    }
}


